﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

namespace BlockMe.Web.MVC.Areas
{
    public class AuthorizedUserAttribute : ActionFilterAttribute, IActionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //TODOHERER
            HttpContextBase context = filterContext.HttpContext;
            RedirectResult redirect = new RedirectResult("~/Account/LogOn");
            if (context.Request.Cookies["bm_token"] == null)
            {
                filterContext.Result = redirect;
            }
            else
            {
                string[] tokens = context.Request.Cookies["bm_token"].Value.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                if (tokens.Length != 2)
                {
                    filterContext.Result = redirect;
                    context.Response.SetCookie(new HttpCookie("bm_token", ""));
                }
                else
                {
                    int uid = 0;
                    uint token = 0;
                    if (!Int32.TryParse(tokens[0],out uid))
                    {
                        filterContext.Result = redirect;
                    }
                    if (!UInt32.TryParse(tokens[1],out token))
                    {
                        filterContext.Result = redirect;
                    }
                    if (!UserHelper.ValidateToken(uid,token))
                    {
                        filterContext.Result = redirect;
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
}